﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace WebApplication1.Services
{
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class GreeterService : Greeter.GreeterBase
    {
        readonly ILogger<GreeterService> _logger;
        readonly JwtTokenVerificationService _jwtTokenVerificationService;
        public GreeterService(ILogger<GreeterService> logger, JwtTokenVerificationService jwtTokenVerificationService)
        {
            _logger = logger;
            _jwtTokenVerificationService = jwtTokenVerificationService;
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            var httpContext = context.GetHttpContext();
            var clientCertificate = httpContext.Connection.ClientCertificate;
            return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
        }
        [AllowAnonymous]
        public override async Task<GetTokenReply> GetToken(GetTokenRequest request, ServerCallContext context)
        {

            var tokenModel = await _jwtTokenVerificationService.GenerateTokenAsync(
                new UserModel
                {
                    PassWord = request.Password,
                    UserName = request.Username
                });
            if (tokenModel.Success)
            {
                return new GetTokenReply
                {
                    Refreshtime = Timestamp.FromDateTime(tokenModel.Refreshtime),
                    Success = tokenModel.Success,
                    Tokenstring = tokenModel.TokenString
                };
            }
            return new GetTokenReply
            {
                Success = tokenModel.Success
            };
        }
    }
}
